<template>
  <div>
    <div>
      <el-button @click="showDialog">新增</el-button>

      <el-dialog v-model="dialogVisible" title="类别的新增" width="30%" :before-close="handleClose">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="类别名称" prop="type">
            <el-input v-model="ruleForm.type" />
          </el-form-item>

          <el-form-item label="图片" prop="img">
            <el-upload
              v-model:file-list="fileList"
              ref="uploadRef"
              class="upload-demo"
              action="/api/uploads"
              :auto-upload="false"
              :limit="1"
              :on-success="success"
              name="filename"
            >
              <template #trigger>
                <el-button type="primary">select file</el-button>
              </template>

              <template #tip>
                <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <el-table :data="typeinfoList" style="width: 100%">
      <el-table-column fixed prop="_id" label="编号" />
      <el-table-column prop="type" label="类别名称" />
      <el-table-column label="图片">
        <template #default="scope">
          <el-image style="width: 200px; height: 100px" :src="'/api/' + scope.row.img"></el-image>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="delByItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { typeinfoAdd, typeinfoQuery, typeinfoDel } from '../service/typeinfoService'
import type { FormInstance, FormRules, UploadInstance, UploadUserFile } from 'element-plus'
const uploadRef = ref<UploadInstance>()
const ruleFormRef = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([])

const typeinfoList = ref<any>([]) //类别数据集合

onMounted(async () => {
  let res = await typeinfoQuery({})
  console.log(res)
  if (res.data.code == 200) {
    typeinfoList.value = res.data.list
  }
})
const delByItem = async (info: any) => {
  //console.log(info);
  let { _id } = info
  let result = await typeinfoDel({ id: _id })
  typeinfoList.value = typeinfoList.value.filter((item: any) => item._id !== _id)
}
const success = async (res: any) => {
  // console.log(res);
  if (res.code == 200) {
    //图片上传成功
    let result = await typeinfoAdd({
      type: ruleForm.type,
      img: res.url
    })
    console.log(result)
    if (result.data.code === 200) {
      //新增成功
      resetForm(ruleFormRef.value as any) //
      console.log(result.data)

      typeinfoList.value = [...typeinfoList.value, ...result.data.data]
    }
  }
}

const submitUpload = () => {
  //手动上传图片的事件
  uploadRef.value!.submit()
}

let dialogVisible = ref<boolean>(false)
const handleClick = () => {
  console.log('click')
}
const showDialog = () => {
  dialogVisible.value = true
}

const ruleForm = reactive({
  type: '',
  img: ''
})
const rules = reactive<FormRules>({
  type: [{ required: true, min: 2, max: 15, message: '请输出长度2到15个字符', trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  //表单提交事件
  if (!formEl) return
  formEl.validate((valid: any) => {
    if (valid) {
      if (fileList.value.length) {
        //判断集合的长度
        submitUpload() //图片上传
      } else {
        alert('请选择图片')
      }

      //表示验证通过
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields() //表单内容重置
  fileList.value = [] //清空 选择的图片
  dialogVisible.value = false //dialog关闭
}
</script>
